#ifndef BERT_THREAD_H
#define BERT_THREAD_H

#include <pthread.h>
#include <string>
#include "Entry.h"
#include "Mutex.h"

/**
 * 线程封装，接口模仿JAVA
 */
class Runnable
{
public:
	/**
	 * Destructor
	 */
	virtual ~Runnable() 
	{
	}
	/**
	 * 线程逻辑在此实现
	 */
	virtual void run() = 0;
};

class Thread: public Runnable, public Entry
{
	/**
	 * 线程唯一id产生器
	 */
	static volatile unsigned int uniqueID ;
	/**
	 * 随机数种子 one per thread
	 */
	unsigned int seed;
	/**
	 * 本线程ID
	 */
	pthread_t m_tid;
	/**
	 * 是否在运行的标志
	 */
	volatile bool running;
	/**
	 * 线程函数，内部调用run
	 */
	static void * threadFunc(void * arg);
	/**
	 * protect pthread_create
	 */
	Mutex mutex;// protect pthread_create

public:
	/**
	 * Constructor
	 */
	Thread(const std::string & name = "Thread");
	/**
	 * Destructor
	 */
	virtual ~Thread();
	/**
	 * 获取本线程id
	 */
	pthread_t getThreadID() { return m_tid; }
	/**
	 * 睡眠 秒
	 */
	static unsigned int sleep( unsigned int seconds);
	/**
	 * 睡眠 毫秒
	 */
	static unsigned int msleep( unsigned int mSeconds);
	/**
	 * 启动线程
	 */
	bool start();
	/**
	 * 等待本线程运行完
	 */
	void join() const;
	/**
	 * 是否在运行
	 */
	bool isAlive() const
	{
		return running;
	}
	/**
	 * 终止线程运行
	 */
	void stop()
	{
		running = false;
	}
	/**
	 * 
	 */
	const char * getClassName() const
	{
		return Entry::name;
	}
};

#endif
